class LuluService {
  constructor() {
    // 模拟用户数据
    this.users = [
      {
        id: 1,
        username: 'admin',
        name: '超级管理员',
        department: 2, // 技术部
        phone: '13800000000',
        email: 'admin@example.com',
        roles: ['超级管理员'],
        status: 0, // 0-启用 1-停用
        remark: '系统默认超级管理员账号',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00',
      },
      {
        id: 2,
        username: 'editor',
        name: '编辑员',
        department: 6, // 研发一组
        phone: '13900000000',
        email: 'editor@example.com',
        roles: ['数据编辑员'],
        status: 0,
        remark: '负责内容编辑工作',
        createTime: '2024-01-02 10:00:00',
        updateTime: '2024-01-02 10:00:00',
      },
      {
        id: 3,
        username: 'viewer',
        name: '查看员',
        department: 3, // 市场部
        phone: '13700000000',
        email: 'viewer@example.com',
        roles: ['数据查看员'],
        status: 1,
        remark: '临时停用，待进一步确认',
        createTime: '2024-01-03 10:00:00',
        updateTime: '2024-01-03 10:00:00',
      },
      {
        id: 4,
        username: 'manager',
        name: '部门经理',
        department: 4, // 财务部
        phone: '13600000000',
        email: 'manager@example.com',
        roles: ['普通管理员'],
        status: 0,
        remark: '财务部门负责人',
        createTime: '2024-01-04 10:00:00',
        updateTime: '2024-01-04 10:00:00',
      },
      {
        id: 5,
        username: 'hr001',
        name: '人事专员',
        department: 5, // 人力资源部
        phone: '13500000000',
        email: 'hr001@example.com',
        roles: ['数据查看员', '数据编辑员'],
        status: 0,
        remark: '负责人事管理工作',
        createTime: '2024-01-05 10:00:00',
        updateTime: '2024-01-05 10:00:00',
      },
    ]

    // 组织数据
    this.organizations = [
      { id: 1, name: '总公司', code: 'HQ', parentId: null, description: '公司总部', sort: 0, status: 0 },
      { id: 2, name: '技术部', code: 'TECH', parentId: 1, description: '负责技术研发', sort: 1, status: 0 },
      { id: 3, name: '市场部', code: 'MKT', parentId: 1, description: '负责市场营销', sort: 2, status: 0 },
      { id: 4, name: '财务部', code: 'FIN', parentId: 1, description: '负责财务管理', sort: 3, status: 0 },
      { id: 5, name: '人力资源部', code: 'HR', parentId: 1, description: '负责人力资源管理', sort: 4, status: 0 },
      { id: 6, name: '研发一组', code: 'DEV1', parentId: 2, description: '前端研发', sort: 1, status: 0 },
      { id: 7, name: '研发二组', code: 'DEV2', parentId: 2, description: '后端研发', sort: 2, status: 0 },
      { id: 8, name: '测试组', code: 'QA', parentId: 2, description: '负责产品测试', sort: 3, status: 0 },
      { id: 9, name: '运维组', code: 'OPS', parentId: 2, description: '负责系统运维', sort: 4, status: 0 },
      { id: 10, name: '北京分公司', code: 'BJ', parentId: null, description: '北京区域业务', sort: 1, status: 0 },
      { id: 11, name: '上海分公司', code: 'SH', parentId: null, description: '上海区域业务', sort: 2, status: 0 },
      { id: 12, name: '广州分公司', code: 'GZ', parentId: null, description: '广州区域业务', sort: 3, status: 0 },
      { id: 13, name: '销售一部', code: 'SALES1', parentId: 10, description: '北京销售一部', sort: 1, status: 0 },
      { id: 14, name: '销售二部', code: 'SALES2', parentId: 10, description: '北京销售二部', sort: 2, status: 0 },
      { id: 15, name: '销售一部', code: 'SALES1_SH', parentId: 11, description: '上海销售一部', sort: 1, status: 0 },
    ]

    this.roles = ['超级管理员', '普通管理员', '数据查看员', '数据编辑员']
  }

  async getKeys(params) {
    try {
      // 这里实现获取keys的业务逻辑
      // 示例返回数据
      return 'aaaaaaaa'
    } catch (error) {
      throw new Error(`获取keys失败: ${error.message}`)
    }
  }

  async login(params) {
    try {
      return {
        token:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE3NDU1ODY2NDEsImV4cCI6MTc0NjE5MTQ0MSwiTmFtZSI6ImFkbWluIiwiSXNBZG1pbiI6IlRydWUiLCJVc2VyTmFtZSI6IueuoeeQhuWRmCIsIlVzZXJJZCI6IjIwMjIwNjAyMjE0NTQ4MTU4MzE2ODc5NDI2NzIzODQiLCJCb29rSWQiOiJBMDAwMDIiLCJCb29rTmFtZSI6IuWYieWFtOi3r-W8l-aWsOadkOaWmeaciemZkOWFrOWPuEEiLCJpc3MiOiJqdWNoZWFwIiwiYXVkIjoianVjaGVhcCJ9.19HQWj0592PbhF8kWtE6_UZzZ2jW_zYK_iiXEobYxW0',
        expire: 604800,
        userInfo: {
          dashboard: '0',
          userId: '2022060221454815831687942672384',
          userName: '管理员',
          role: ['SA', 'admin', 'Auditor'],
          bookName: '嘉兴路弗新材料有限公司A',
        },
      }
    } catch (error) {
      throw new Error(`登录失败: ${error.message}`)
    }
  }

  async getMenus(params) {
    try {
      // 这里实现获取用户菜单的业务逻辑
      // 示例菜单数据
      return [
        {
          id: 1,
          name: 'Lulu首页',
          path: '/lulu/dashboard',
          icon: 'dashboard',
          children: [],
        },
        {
          id: 2,
          name: 'Lulu管理',
          path: '/lulu/management',
          icon: 'setting',
          children: [
            {
              id: 21,
              name: '用户管理',
              path: '/lulu/management/users',
              icon: 'user',
            },
            {
              id: 22,
              name: '权限管理',
              path: '/lulu/management/permissions',
              icon: 'lock',
            },
          ],
        },
        {
          id: 3,
          name: 'Lulu数据',
          path: '/lulu/data',
          icon: 'data',
          children: [],
        },
      ]
    } catch (error) {
      throw new Error(`获取菜单失败: ${error.message}`)
    }
  }

  // 账号管理相关方法

  // 获取用户列表
  async getUserList(params = {}) {
    try {
      const { page = 1, pageSize = 10, name = '', username = '', department = '', status = '', roles = '' } = params

      // 过滤数据
      let filteredUsers = [...this.users]

      // 按姓名搜索
      if (name) {
        filteredUsers = filteredUsers.filter((user) => user.name.toLowerCase().includes(name.toLowerCase()))
      }

      // 按用户名搜索
      if (username) {
        filteredUsers = filteredUsers.filter((user) => user.username.toLowerCase().includes(username.toLowerCase()))
      }

      // 按部门过滤
      if (department) {
        filteredUsers = filteredUsers.filter((user) => user.department === parseInt(department))
      }

      // 按状态过滤
      if (status !== '') {
        filteredUsers = filteredUsers.filter((user) => user.status === parseInt(status))
      }

      // 按角色过滤
      if (roles) {
        filteredUsers = filteredUsers.filter((user) => user.roles.some((role) => role.includes(roles)))
      }

      // 分页
      const total = filteredUsers.length
      const startIndex = (page - 1) * pageSize
      const endIndex = startIndex + pageSize
      const list = filteredUsers.slice(startIndex, endIndex)

      // 添加部门名称
      const listWithDeptName = list.map((user) => ({
        ...user,
        departmentName: this.getDepartmentName(user.department),
      }))

      return {
        list: listWithDeptName,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        totalPages: Math.ceil(total / pageSize),
      }
    } catch (error) {
      throw new Error(`获取用户列表失败: ${error.message}`)
    }
  }

  // 创建用户
  async createUser(userData) {
    try {
      // 验证用户名是否已存在
      const existingUser = this.users.find((user) => user.username === userData.username)
      if (existingUser) {
        throw new Error('用户名已存在')
      }

      // 验证邮箱是否已存在
      if (userData.email) {
        const existingEmail = this.users.find((user) => user.email === userData.email)
        if (existingEmail) {
          throw new Error('邮箱已存在')
        }
      }

      const newUser = {
        id: Date.now(),
        username: userData.username,
        name: userData.name,
        department: userData.department,
        phone: userData.phone || '',
        email: userData.email || '',
        roles: userData.roles || [],
        status: userData.status !== undefined ? userData.status : 0,
        remark: userData.remark || '',
        createTime: new Date().toLocaleString('zh-CN'),
        updateTime: new Date().toLocaleString('zh-CN'),
      }

      this.users.push(newUser)
      return newUser
    } catch (error) {
      throw new Error(`创建用户失败: ${error.message}`)
    }
  }

  // 更新用户
  async updateUser(id, userData) {
    try {
      const userIndex = this.users.findIndex((user) => user.id === parseInt(id))
      if (userIndex === -1) {
        throw new Error('用户不存在')
      }

      // 如果更新邮箱，检查是否与其他用户重复
      if (userData.email) {
        const existingEmail = this.users.find((user) => user.email === userData.email && user.id !== parseInt(id))
        if (existingEmail) {
          throw new Error('邮箱已存在')
        }
      }

      const updatedUser = {
        ...this.users[userIndex],
        ...userData,
        updateTime: new Date().toLocaleString('zh-CN'),
      }

      this.users[userIndex] = updatedUser
      return updatedUser
    } catch (error) {
      throw new Error(`更新用户失败: ${error.message}`)
    }
  }

  // 删除用户
  async deleteUser(id) {
    try {
      const userIndex = this.users.findIndex((user) => user.id === parseInt(id))
      if (userIndex === -1) {
        throw new Error('用户不存在')
      }

      // 不允许删除超级管理员
      if (this.users[userIndex].roles.includes('超级管理员')) {
        throw new Error('不能删除超级管理员账号')
      }

      this.users.splice(userIndex, 1)
      return { message: '用户删除成功' }
    } catch (error) {
      throw new Error(`删除用户失败: ${error.message}`)
    }
  }

  // 更新用户状态
  async updateUserStatus(id, status) {
    try {
      const userIndex = this.users.findIndex((user) => user.id === parseInt(id))
      if (userIndex === -1) {
        throw new Error('用户不存在')
      }

      // 不允许停用超级管理员
      if (status === 1 && this.users[userIndex].roles.includes('超级管理员')) {
        throw new Error('不能停用超级管理员账号')
      }

      this.users[userIndex].status = status
      this.users[userIndex].updateTime = new Date().toLocaleString('zh-CN')

      return {
        message: status === 0 ? '用户已启用' : '用户已停用',
        user: this.users[userIndex],
      }
    } catch (error) {
      throw new Error(`更新用户状态失败: ${error.message}`)
    }
  }

  // 重置密码
  async resetPassword(id) {
    try {
      const userIndex = this.users.findIndex((user) => user.id === parseInt(id))
      if (userIndex === -1) {
        throw new Error('用户不存在')
      }

      // 模拟重置密码操作
      this.users[userIndex].updateTime = new Date().toLocaleString('zh-CN')

      return {
        message: '密码重置成功，新密码已发送到用户邮箱',
        newPassword: '123456Aa!', // 实际项目中不应该返回密码
      }
    } catch (error) {
      throw new Error(`重置密码失败: ${error.message}`)
    }
  }

  // 获取用户详情
  async getUserById(id) {
    try {
      const user = this.users.find((user) => user.id === parseInt(id))
      if (!user) {
        throw new Error('用户不存在')
      }

      return {
        ...user,
        departmentName: this.getDepartmentName(user.department),
      }
    } catch (error) {
      throw new Error(`获取用户详情失败: ${error.message}`)
    }
  }

  // 获取组织列表
  async getOrganizations() {
    try {
      return this.organizations.filter((org) => org.status === 0)
    } catch (error) {
      throw new Error(`获取组织列表失败: ${error.message}`)
    }
  }

  // 获取角色列表
  async getRoles() {
    try {
      return this.roles
    } catch (error) {
      throw new Error(`获取角色列表失败: ${error.message}`)
    }
  }

  // 根据部门ID获取部门名称
  getDepartmentName(departmentId) {
    const dept = this.organizations.find((org) => org.id === departmentId)
    return dept ? dept.name : ''
  }

  // 构建组织树
  buildOrgTree(orgs = this.organizations, parentId) {
    return orgs
      .filter((org) => org.parentId === parentId && org.status === 0)
      .sort((a, b) => a.sort - b.sort)
      .map((org) => {
        const children = this.buildOrgTree(orgs, org.id)
        return {
          title: org.name,
          key: org.id.toString(),
          value: org.id,
          children: children.length > 0 ? children : undefined,
          isLeaf: children.length === 0,
        }
      })
  }

  // 获取组织树数据
  async getOrgTree() {
    try {
      return this.buildOrgTree()
    } catch (error) {
      throw new Error(`获取组织树失败: ${error.message}`)
    }
  }

  // 重定向到 React 官网
  async redirectToReact() {
    try {
      return {
        redirectUrl: 'https://react.dev/',
        message: '正在重定向到 React 官网',
      }
    } catch (error) {
      throw new Error(`重定向失败: ${error.message}`)
    }
  }

  // 生成图片验证码
  async generateImageCode() {
    try {
      const captchaGenerator = require('../../utils/captcha.js')
      const result = captchaGenerator.generate()

      return {
        code: result.code,
        image: result.image,
      }
    } catch (error) {
      throw new Error(`生成验证码失败: ${error.message}`)
    }
  }
}

module.exports = new LuluService()
